package test;

import junit.framework.TestCase;

/**
 * 变位词(anagrams)
 *
 * @author fireway
 *
 */
public class AnagramTestCase extends TestCase {
    public void test() {
        String s = "abc";
        doAnagram(s);
    }

    private void doAnagram(String s) {
        char[] a = s.toCharArray();
        permute(a, 0, s.length() -1);
    }

    private void swap(char[] a, int m, int n) {
        char t = a[m];
        a[m] = a[n];
        a[n] = t;
    }

    private void permute(char[] a, int m, int n) {
        if (m == n) {
            printResult(a);
        } else {
            for (int i = m; i <= n; i++) {
                if (m != i) {
                    swap(a, m, i);
                }

                permute(a, m + 1, n);

                if (m != i) {
                    swap(a, m, i);
                }
            }
        }
    }

    private void printResult(char[] text) {
        for (int i = 0; i < text.length; i++) {
            System.out.print(text[i]);
        }
        System.out.println();
    }
}
